<template>
  <div class="main_content">
    <el-scrollbar style="height: 85%; width: 100%; margin-top: -40px">
      <div ref="consoleOutput" class="console-output" @scroll="handleScroll">
        <p v-for="(log, index) in logs" :key="index" :style="{ color: log.color }">
          {{ log.timestamp }} : {{ log.message }}
        </p>
      </div>
    </el-scrollbar>
  </div>
</template>

<script>
export default {
  name: 'AllLogList',
  data() {
    return {
      logs: [],
      query: {
        type: 4
      },
      intervalId: null,
      fetchCount: 0,
      maxFetchCount: 100,
      userScrolled: false,
      scrollThreshold: 100, // 阈值，单位：像素,
      is_realtime: false
    };
  },
  watch: {
    logs() {
      this.scrollToBottom();
    }
  },
  props: {
    qtCall: {
      type: Object,
      default: null
    }
  },
  mounted() {
    if (process.env.NODE_ENV === 'production') {
      setTimeout(() => {
        if (this.qtCall) {
          this.logs = [];
          this.query.type = 4;
          this.qtCall.JsToQt("NeedLogs", this.query);
          this.getExistingLogs();
        }
      }, 200);
    } else {
      this.getExistingLogs();
    }
  },
  beforeDestroy() {
    this.clearFetchInterval();
  },
  methods: {
    getExistingLogs() {
      if (process.env.NODE_ENV === 'production') {
        this.qtCall.QtToJs.connect((func, json) => {
          if (func === "RefreshNearLog") {
            const datas = JSON.parse(json);
            if (datas.code === 200) {
              console.log("RefreshNearLog updateLogs: ", datas.data["logs"])
              this.updateLogs(datas.data["logs"]);
              this.getRealtimeLogs();
            }
          }
        });
      } else {
        const logs = [
          {
            "dateTime": "2024-12-16 01:00:00-000",
            "type": 2,
            "color": "#F1313E",
            "log": "日志输出1"
          },
          {
            "dateTime": "2024-12-16 01:00:10-123",
            "type": 1,
            "color": "#FA6400",
            "log": "日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2"
          },
          {
            "dateTime": "2024-12-16 01:00:10-123",
            "type": 3,
            "color": "#FA6400",
            "log": "日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2日志输出2"
          },

        ];
        this.updateLogs(logs);
        this.startFetchingLogs();
      }
    },
    startFetchingLogs() {
      this.intervalId = setInterval(() => {
        if (this.fetchCount >= this.maxFetchCount) {
          this.clearFetchInterval();
          return;
        }
        this.getRealtimeLogs();
        this.fetchCount++;
      }, 1000);
    },
    clearFetchInterval() {
      if (this.intervalId) {
        clearInterval(this.intervalId);
        this.intervalId = null;
      }
    },
    getRealtimeLogs() {
      if (process.env.NODE_ENV === 'production') {
        if (!this.is_realtime) {
          this.is_realtime = true;
          this.qtCall.QtToJs.connect((func, json) => {
            if (func === "RefreshLastLog") {
              const datas = JSON.parse(json);
              if (datas.code === 200) {
                console.log("ALL Logs RefreshLastLog: ", this.logs)
                console.log("all log refresh Near log: ", datas.data["logs"])
                this.updateLogs(datas.data["logs"]);
              }
            }
          });
        }
      } else {
        const last_logs = [
          {
            "dateTime": "2024-12-16 01:00:00-000",
            "type": 1,
            "color": "#2A2A2A",
            "log": "日志输出1"
          },
          {
            "dateTime": "2024-12-16 01:00:10-123",
            "color": "#F1313E",
            "type": 2,
            "log": "日志输出2"
          },
          {
            "dateTime": "2024-12-16 01:00:10-123",
            "color": "#02ff15",
            "type": 3,
            "log": "日志输出3"
          }
        ]
        this.updateLogs(last_logs);
      }
    },
    updateLogs(logs) {
      this.logs.push(...logs.map(log => {
        if ( log.type === 11 ) return null; // 跳过数据
        return {
          timestamp: log.dateTime,
          message: log.log,
          color: log.color
        }
      }).filter(log => log !== null));
      this.scrollToBottom();
    },
    handleScroll() {
      const consoleOutput = this.$refs.consoleOutput;
      this.userScrolled = consoleOutput.scrollTop + consoleOutput.clientHeight + this.scrollThreshold < consoleOutput.scrollHeight;
    },
    scrollToBottom() {
      this.$nextTick(() => {
        setTimeout(() => {
          const consoleOutput = this.$refs.consoleOutput;
          if (consoleOutput && !this.userScrolled) {
            consoleOutput.scrollTop = consoleOutput.scrollHeight;
          }
        }, 100); // 设置延迟，确保 DOM 渲染完成
      });
    }
  }
};
</script>

<style scoped>
.main_bottom .main_right .main_content{
  padding: 0px;
  width: 100%;
}

.console-output {
  margin-top: 35px;
  max-height: 790px;
  overflow-y: auto;
  overflow-x: hidden;
  word-break: break-word;
}

.console-output p {
  margin: 0;
  padding: 5px 0;
}

.el-scrollbar__wrap {
  overflow-x: hidden !important;
}
</style>
